package cn.quevo.core.file.text;

import cn.quevo.core.exception.CheckParamsException;
import cn.quevo.core.file.FileUtils;
import cn.quevo.core.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 文本文件读取
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2018/08/01 11:19:35
 * @Copyright 东方浩星（北京）传媒科技有限公司版权所有.All Rights Reserved.
 */
public class PDF {
    private final static Logger log = LoggerFactory.getLogger(PDF.class);

    public static String getContent(File file, String... passwd) {
        if (file == null || !file.isFile()) {
            throw new CheckParamsException(6021, "文件不存在");
        }
        String fileExt = FileUtils.getFileSuffix(file.getName());
        if (!".pdf".equalsIgnoreCase(fileExt)) {
            throw new CheckParamsException(6020, "文件非PDF格式文档");
        }
        try (InputStream inputStream = new FileInputStream(file);) {
            return getContent(inputStream,fileExt, passwd);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6022, "文件不存在");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6023, "文件读取失败");
        }
    }

    public static String getContent(InputStream inputStream,String fileExt, String... passwd) {
        fileExt = FileUtils.getFileSuffix(fileExt);
        if (!".pdf".equalsIgnoreCase(fileExt)) {
            throw new CheckParamsException(6020, "文件非PDF格式文档");
        }
        String pwd = passwd == null || passwd.length <= 0 ? "" : StringUtils.valueOf(passwd[0]).trim();
        try (PDDocument document = PDDocument.load(inputStream, pwd)) {
            return getContent(document);
        } catch (InvalidPasswordException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6021, "文档被加密，且密码无效");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6022, "文件解析失败，文件非PDF格式文档");
        }
    }

    private static String getContent(PDDocument document) {
        document.getClass();
        try {
            if (!document.isEncrypted()) {
                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition(true);
                PDFTextStripper tStripper = new PDFTextStripper();
                return tStripper.getText(document);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6024, "文件解析失败，文件非PDF格式文档");
        }
        throw new CheckParamsException(6023, "文件已被加密，无法读取");
    }
}
